package cn.msn.user.service.impl;

import cn.msn.basic.exception.BusinessException;
import cn.msn.basic.util.Md5Utils;
import cn.msn.basic.util.StrUtils;
import cn.msn.user.domain.Logininfo;
import cn.msn.user.domain.User;
import cn.msn.user.dto.UserDto;
import cn.msn.user.dto.UserEmailDto;
import cn.msn.user.mapper.LogininfoMapper;
import cn.msn.user.mapper.UserMapper;
import cn.msn.user.service.IUserService;
import cn.msn.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String rePwd = userDto.getRePwd();
        // 1. 空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) ||
                StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)){
            throw new BusinessException("信息不能为空");
        }
        // 2.校验密码是否一致
        if (!pwd.equals(rePwd)){
            throw new BusinessException("密码不一致");
        }
        // 3.校验短信验证码是否过期、正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + phone);
        if (codeObj == null){
            throw new BusinessException("短信验证码过期");
        }
        if (!codeObj.toString().split(":")[0].equals(phoneCode)){
            throw new BusinessException("短信验证码错误");
        }
        // 4.保存到数据库
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        // 4.1 先添加logininfo，获取自增ID
        logininfoMapper.save(logininfo);
        // 4.2 再添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailRegister(UserEmailDto userEmailDto) {
        String email = userEmailDto.getEmail();
        String emaiCode = userEmailDto.getEmaiCode();
        String password = userEmailDto.getPassword();
        String passwordRepeat = userEmailDto.getPasswordRepeat();
        // 1.空值校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(emaiCode) ||
                StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("内容不能为空");
        }
        // 2.校验密码
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("密码不一致");
        }
        // 3.校验短信验证码是否过期、正确
        Object codeObj = redisTemplate.opsForValue().get("register:" + email);
        if (codeObj == null){
            throw new BusinessException("邮箱验证码过期");
        }
        if (!codeObj.toString().split(":")[0].equals(emaiCode)){
            throw new BusinessException("邮箱验证码错误");
        }
        // 4.保存到数据库
        User user = userEmailDto2User(userEmailDto);
        Logininfo logininfo = user2Logininfo(user);
        // 4.1 先添加logininfo，获取自增ID
        logininfoMapper.save(logininfo);
        // 4.2 再添加user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    private User userEmailDto2User(UserEmailDto userEmailDto) {
        // 创建user对象
        User user = new User();
        user.setUsername(userEmailDto.getEmail());
        user.setEmail(userEmailDto.getEmail());
        // 生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userEmailDto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }


    private User userDto2User(UserDto userDto) {
        // 创建user对象
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        // 生成随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        // 拷贝
        BeanUtils.copyProperties(user,logininfo);
        // 添加用户
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    @Override
    @Transactional
    public void save(User user) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);

        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);

        //保存user
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }


    @Override
    @Transactional
    public void remove(Long id) {
        // 删除登录信息logininfo
        User user = userMapper.loadById(id);
        logininfoMapper.remove(user.getLogininfoId());
        // 删除user信息
        userMapper.remove(id);
    }

    @Override
    @Transactional
    public void update(User user) {
        // 处理盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(user.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        super.update(user);

        // 获取登录信息id
        Long logininfoId = userMapper.loadById(user.getId()).getLogininfoId();

        // 创建logininfo
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);//id,type ,state
        // 将新的数据覆盖旧的数据
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.update(logininfo);
    }
}
